package org.funtester.performance.books.chapter04.section2;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * 使用callback解析异步HTTP客户端响应
 */
public class AsyncHttpClientCallbackDemo {

    public static void main(String[] args) throws IOException, InterruptedException {
        CloseableHttpAsyncClient httpAsyncClient = HttpAsyncClients.createDefault();// 创建异步HTTP客户端
        httpAsyncClient.start();// 启动异步HTTP客户端
        JSONObject params = new JSONObject();// 创建存放参数的JSON对象
        params.put("start", 0);// 添加参数
        params.put("pageSize", 10);// 添加参数
        HttpGet httpGet = HttpRequestTool.getHttpGet("http://localhost:8080/query", params);// 创建httpget请求对象
        httpAsyncClient.execute(httpGet, new FutureCallback<HttpResponse>() {
            @Override
            public void completed(HttpResponse httpResponse) {
                HttpEntity entity = httpResponse.getEntity();// 获取响应实体
                String str = null;// 响应内容
                try {
                    str = EntityUtils.toString(entity);// 获取响应实体内容
                    EntityUtils.consume(entity);// 关闭响应实体
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                System.out.println(Thread.currentThread().getName() + "  " + str);// 打印响应内容
            }

            @Override
            public void failed(Exception e) {
                System.out.println("请求失败  " + e.getMessage());// 打印失败信息
            }

            @Override
            public void cancelled() {
                System.out.println("请求取消");// 打印取消信息
            }
        });
        Thread.sleep(1000);// 等待异步请求完成,打印日志
        httpAsyncClient.close();
    }

}
